﻿using System.Xml.Linq;
using NJabber.Stream.Elements;

namespace NJabber.Stream.Elements
{
    public abstract class ErrorElementTestBase : XmppStreamElementTestBase
    {
        private string errorInfoNamespace;

        protected ErrorElementTestBase(string errorInfoNamespace, string elementNamespaceName, string elementNamespaceUri) : base("error", elementNamespaceUri, elementNamespaceName)
        {
            this.errorInfoNamespace = errorInfoNamespace;
        }

        public string ErrorInfoNamespace
        {
            get { return errorInfoNamespace; }
        }

        protected XmppStreamElement CreateErrorElementDetails(string name, string uri)
        {
            return new XmppStreamElementImpl(name, uri);
        }

        protected XElement CreateErrorXElement(string errorName)
        {
            return CreateErrorXElement(errorName, "");
        }

        protected XElement CreateErrorXElement(string errorName, string errorDescription)
        {
            return CreateErrorXElement(errorName, errorDescription, "");
        }

        protected XElement CreateErrorXElement(string errorName, string errorDescription, string errorDescriptionLang)
        {
            return CreateErrorXElement(errorName, errorDescription, errorDescriptionLang, "", "");
        }

        protected XElement CreateErrorXElement(string errorName, string errorDescription, string errorDescriptionLang, string errorDetailsName, string errorDetailsUri)
        {
            XElement errorElement = CreateXElement(Name, XmlNamespace.Name, XmlNamespace.Uri);
            AttachErrorName(errorElement, errorName);
            if (!string.IsNullOrEmpty(errorDescription)) AttachErrorDescription(errorElement, errorDescription, errorDescriptionLang);
            if (!string.IsNullOrEmpty(errorDetailsName) && 
                !string.IsNullOrEmpty(errorDetailsUri)) AttachErrorDetails(errorElement, errorDetailsName, errorDetailsUri);
            return errorElement;
        }

        private void AttachErrorName(XElement errorElement, string errorName)
        {
            errorElement.Add(CreateXElement(errorName, "", ErrorInfoNamespace));
        }

        private void AttachErrorDescription(XElement errorElement, string errorDescription, string errorDescriptionLang)
        {
            XElement description = CreateXElement("text", "", ErrorInfoNamespace);
            if (!string.IsNullOrEmpty(errorDescriptionLang)) description.SetAttributeValue(XNamespace.Xml + "lang", errorDescriptionLang);
            description.SetValue(errorDescription);
            errorElement.Add(description);
        }

        private void AttachErrorDetails(XElement errorElement, string errorDetailsName, string errorDetailsUri)
        {
            XElement errorDetails = CreateXElement(errorDetailsName, "", errorDetailsUri);
            errorElement.Add(errorDetails);
        }
    }
}
